package org.umss.fixture.activities;

import org.umss.fixture.R;
import org.umss.fixture.model.Championship;
import org.umss.fixture.services.FixtureBuilderServices;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class NewChampionshipActivity extends Activity {

	private Championship newChampionship;
	private static ProgressDialog progressDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_championship);
		progressDialog = new ProgressDialog(this);
		final Button button = (Button) findViewById(R.id.createChampionsipButton);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				TextView nameField = (TextView) findViewById(R.id.nameField);
				TextView teamsField = (TextView) findViewById(R.id.teamsField);
				newChampionship = new Championship(nameField.getText().toString(), Integer.parseInt(teamsField.getText().toString()));
				new SaveChampionshipTask().execute();
			}
		});
	}
	
	private class SaveChampionshipTask extends AsyncTask<Void, Void, Void> {

		@Override
		public void onPreExecute() {
			if (progressDialog != null) {
				progressDialog.setIndeterminate(true);
				progressDialog.setCancelable(false);
				progressDialog.setMessage("Saving championship...");
				progressDialog.show();
			}
		}

		@Override
		protected Void doInBackground(Void... params) {
			FixtureBuilderServices services = new FixtureBuilderServices();
			services.saveChampionship(newChampionship);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			finish();
			if (progressDialog != null) {
				progressDialog.dismiss();
			}

			progressDialog = null;
		}
	}

	
}
